import createHandler from "./request"
import {fuzzyQuery, insertOne, queryOne, selectAll} from "./fake-db"
import {v4} from "uuid"
import {now} from "../utils/time"
import encrypt from "../utils/encrypt"

const getAllUser = createHandler(() => {
    return {
        code: 0,
        data: selectAll('user')
    }
})

const setUserEnable = createHandler((uid, enable) => {
    const user = queryOne('user', 'uid', uid)
    if (user) user.enable = enable
    return {
        code: 0
    }
})

const deleteUser = createHandler(uid => {
    const users = selectAll('user')
    const index = users.findIndex(user => user.uid === uid)
    if (index !== -1) {
        users.splice(index, 1)
    }
    return {
        code: 0
    }
})

const changeUser = createHandler((id, {uid, name, email, password, role}) => {
    const user = queryOne('user', 'id', id)
    if (!user) return {
        code: 4001,
        msg: '角色不存在'
    }
    let tempUser = queryOne('user', 'uid', uid)
    if (tempUser && tempUser.id !== id) return {
        code: 4002,
        msg: '账号重复'
    }
    tempUser = queryOne('user', 'email', email)
    if (tempUser && tempUser.id !== id) return {
        code: 4003,
        msg: '邮箱重复'
    }
    user.uid = uid
    user.name = name
    user.email = email
    user.role = role
    if (password) {
        user.password = encrypt(password)
    }
    return {
        code: 0
    }
})

const createUser = createHandler(({uid, name, email, password, role}) => {
    if (queryOne('user', 'uid', uid)) return {
        code: 4002,
        msg: '账号重复'
    }
    if (queryOne('user', 'email', email)) return {
        code: 4003,
        msg: '邮箱重复'
    }
    const user = {
        id: v4(),
        uid,
        name,
        email,
        password: encrypt(password),
        role,
        created_at: now(),
        last_login_at: "1/1/1 00:00:00",
        enable: true
    }
    insertOne('user', user)
    return {
        code: 0
    }
})

const queryUser = createHandler(uidOrName => {
    const users1 = fuzzyQuery('user', 'uid', uidOrName)
    const users2 = fuzzyQuery('user', 'name', uidOrName)
    const users = users1.length >= users2.length ? [...users1, ...users2] : [...users2, ...users1]
    const map = new Map()
    users.forEach(user => map.set(user.id, user))
    return {
        code: 0,
        data: Array.from(map.values())
    }
})

export {getAllUser, setUserEnable, deleteUser, changeUser, createUser, queryUser}